#!/usr/bin/env python3

import os 
import time
import sys
import json
import configparser
import hashlib
import time
import datetime
import base64
import dbus
from binascii import a2b_hex
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

# 检查是否传递了足够的参数
#arg1 : status(0:修复前、1:修复后、2:修复失败)
#arg2 : 失败原因
#arg3 : 脚本报错输出
if len(sys.argv) != 4:
    print("请至少传递一个参数。")
    sys.exit(1)

# 获取传递的参数
fixStatus = sys.argv[1]
failResult = sys.argv[2]
failOutput = sys.argv[3]

systemVersion = ""
osVersion=""
patchVersion=""
host_mac=""
serialNumber=""
debList = ""
#获取系统版本
try:
    with open ("/etc/kylin-build", 'r') as file:
        for line in file:
            if "buildid" in line:
                systemVersion = line.replace("buildid:","").strip()
        if systemVersion == "":
            systemVersion = "2107"
    with open("/etc/os-release", 'r') as file:
        for line in file:
            if "KYLIN_RELEASE_ID=" in line:
                osVersion = line.replace("KYLIN_RELEASE_ID=","").strip()
except:
   pass

#补丁版本
try:
    with open ("/etc/kylin-version/kylin-system-version.conf", 'r') as file:
        for line in file:
            if "update_version" in line:
                patchVersion = line.replace("update_version","").replace("=","").strip()
except:
    patchVersion=""
#服务序列号       
with open ("/etc/.kyinfo", 'r') as file:
    for line in file:
        if "key=" in line:
            osVersion = line.replace("key=","").strip()
#mac地址   
mac = os.popen("cat /sys/class/net/$(ip route show default | awk '/default/ {print $5}')/address").readlines()
if mac:
    host_mac = mac[0].strip()
#dpkg -l 列表
debList = os.popen("dpkg -l").read()

#构造json
 #获取当前时间
# UTC时间
utc_time = datetime.datetime.utcnow()
# 转时间字符串
utc_time = utc_time.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
time_suffix = utc_time.split(".")[1]
# 字符串转时间元祖
utc_time = time.strptime(utc_time, "%Y-%m-%d %H:%M:%S.%f")
# 时间元祖转时间戳
utc_time = time.mktime(utc_time)
# 生成东八区时间时间戳
now_time = utc_time + 8*60*60
# 时间戳转时间元祖
now_time = time.localtime(now_time)
# 时间元祖转字符串
now_time = time.strftime("%Y-%m-%d %H:%M:%S",now_time)
now_time = now_time + "." +time_suffix

sendInfoJson={"fixStatus":fixStatus,"fixResult":failResult,"failOutput":failOutput,"mac":host_mac,"systemVersion":systemVersion,"osVersion":osVersion,"patchVersion":patchVersion,"serialNumber":serialNumber,"debList":debList,"createTimeStamp":now_time}
sendInfo=json.dumps(sendInfoJson)

#构建packageInfo
tid=""


packageInfoJson={"packageName":"kylin-system-updater","messageType":"fix-error","tid":tid}
packageInfo=json.dumps(packageInfoJson)


#获取sha256的值
hsobj = hashlib.sha256()
try:
    hsobj.update(sendInfo.encode("utf-8"))
except ValueError as e:
    print("SHA256 value error: %s.",str(e))
except Exception as e:
    print(str(e))

key="LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlHZk1BMEdDU3FHU0liM0RRRUJBUVVBQTRHTkFE\
Q0JpUUtCZ1FDN0d3Tnhla3B5elV4amJCVitaM1BOMnExRApiZkdFQkVwTVVhdVI0TzNoUlNXeFlI\
TjVvYkdseS9vemdPbTZ2NGdIcFkxMSsrRWZUOW5PSTVlVkc3YWxicGVUClBaSkNEeTR2dGEvU2Zh\
aEM2ajZ1TVJja2pta0o2THpsUHZwTFJkZFUwY3NTT3ppRk9veUNZK01nVjlZOUt2dTMKM3BjNXBB\
VWx1U1NNdUtoYjN3SURBUUFCCi0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQo="

try:
    # 计算hex值
    value_hex = a2b_hex(hsobj.hexdigest())
    # 加载公钥,填充格式OAEP
    uniqueKey = key.encode('utf-8')
    uniqueKeyorig = base64.b64decode(uniqueKey)  # 公钥文件
    rsa_pubkey = RSA.importKey(uniqueKeyorig)    # RSA公钥
    oaep_pub = PKCS1_OAEP.new(rsa_pubkey)        # OAEP填充
    # 加密数据
    encodemsg = oaep_pub.encrypt(value_hex)
    # 加密数据Base64转码
    enMsg = base64.b64encode(encodemsg)
except ValueError:
    print("Value error: %s.", hsobj.hexdigest())
except TypeError:
    print("RSA key has no private half.")
try:
    bus = dbus.SystemBus()
    remote_object = bus.get_object("com.kylin.daq",
                                "/com/kylin/daq")

# you can either specify the dbus_interface in each call...
    reply_List = remote_object.UploadMessage(packageInfo,sendInfo,enMsg,dbus_interface = "com.kylin.daq.interface")
except dbus.DBusException as e:
    print("kylin-daq dbus call failed,",str(e))


